package com.qianyucc.blog.controller.admin;

import cn.hutool.core.io.*;
import com.qianyucc.blog.exception.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.util.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * @author lijing
 * @e-mail 1413979079@qq.com
 * @date 2020-01-12 19:16
 * @description 自定义图床
 */
@Slf4j
@RestController
@RequestMapping("/admin/image")
public class ImageController {
    @Value("${blog.images.path}")
    private String imagesPath;
    @Value("${blog.url}")
    private String uri;

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public String upload(@RequestParam("image") MultipartFile multipartFile) {
        // "." 、"\"、"|"需要转义
        String[] split = multipartFile.getOriginalFilename().split("\\.");
        String fileName = UUID.randomUUID().toString() + "." + split[split.length - 1];
        try {
            File dir = new File(imagesPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileUtil.writeFromStream(multipartFile.getInputStream(), imagesPath + fileName);
            String url = uri + "admin/image/get/" + fileName;
            log.debug("image-url:{}", url);
            return url;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ImageUploadFailureException(e);
        }
    }

    @ApiOperation("根据图片地址获取图片")
    @GetMapping("/get/{fileName}.{type}")
    public void get(HttpServletResponse res, @PathVariable String fileName, @PathVariable String type) {
        BufferedInputStream in = null;
        ServletOutputStream out = null;
        try {
            in = FileUtil.getInputStream(imagesPath + fileName + "." + type);
            out = res.getOutputStream();
            StreamUtils.copy(in, out);
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
        }
    }
}
